package com.guoyu.project.common.utils;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
	public static String uploadFile( MultipartFile multipartFile , HttpSession session , String path) throws IOException{
		String projectPath = session.getServletContext().getRealPath("/");
		String webApps = new File(projectPath).getParent();
		String[] strs =  multipartFile.getOriginalFilename().split("\\.");
		String name = UUID.randomUUID().toString() + "." +  strs[strs.length - 1];
		File file = new File(webApps + path + name);
		FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
		return name;
	}
	
	public static String getFileSize(MultipartFile multipartFile){
		long size = multipartFile.getSize();
		if( size / 1024 < 1 ) return size + "B";
		if( size / 1024 / 1024 < 1) return String.format("%.2f", size/1024.0) + "K";
		if( size / 1024 / 1024 / 1024 < 1 )  return String.format("%.2f", size/1024.0/1024.0) + "M";
		return  String.format("%.2f", size/1024.0/1024.0/1024.0) + "G";
	}
}
